package stock;

import javax.persistence.EntityManagerFactory;

import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.stereotype.Component;

@Component("contextUtil")
public class ContextUtil implements ApplicationContextAware {

	private static ApplicationContext context;

	public static SessionFactory sessionFactory1 = null;

	public static SessionFactory getSessionFactory1() {
		if (sessionFactory1 == null) {
			EntityManagerFactory en = (EntityManagerFactory) context.getBean("entityManagerFactory");
			HibernateTransactionManager h = new HibernateTransactionManager();
			sessionFactory1 = en.unwrap(SessionFactory.class);
		}
		return sessionFactory1;
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	public static ApplicationContext getContext() {
		return context;
	}

	public static Object getBean(String beanName) {
		return context.getBean(beanName);
	}

	public static HibernateTransactionManager getSessionFactory() {
		EntityManagerFactory en = (EntityManagerFactory) context.getBean("entityManagerFactory");
		HibernateTransactionManager h = new HibernateTransactionManager();
		h.setSessionFactory(en.unwrap(SessionFactory.class));
		return h;
	}

}
